<template>
  <div class="container"  v-loading="loading" element-loading-text="登录系统中"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <div class="to-login-container">
      <!--
      <div class="left" :style="{'background-image': 'url(' + currentSideUrl + ')'}"></div>
      -->
      <div class="right">
        <el-header class="welcome"><a style="color: #A71E32">落实全面从严治党主体责任</a></el-header>
        <el-header class="header">评价系统</el-header>
        <div style="text-align: center;padding: 10px;margin-right: 20px">
          <el-image :src="loginForm.avatarUrl" style="width: 100px;height: 100px;border-radius: 50px;" lazy>
            <template #error>
              <img src="static/avatar.png" style="width: 100px;height: 100px;border-radius: 50px;" >
            </template>
            <template #placeholder>
              <img src="static/avatar.png" style="width: 100px;height: 100px;border-radius: 50px;" >
            </template>
          </el-image>
        </div>
        <el-form ref="refLoginForm" :model="loginForm" class="loginForm" :rules="loginRules">
          <el-form-item prop="loginname">
            <el-autocomplete
                ref="refLoginname"
                v-model="loginForm.loginname"
                placeholder="登录账号"
                name="loginname"
                type="text"
                :fetch-suggestions="querySearch"
                tabindex="1"
                :trigger-on-focus="false"
                :suffix-icon="ArrowDownBold"
                auto-complete="on"
                @focus="queryNormalUser"
                @select="handleSelect">
            </el-autocomplete>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
                ref="refPassword"
                v-model="loginForm.password"
                placeholder="登录密码"
                name="password"
                type="text"
                tabindex="1"
                show-password
                auto-complete="on"
                @keyup.enter="handleLogin(refLoginForm)"></el-input>
          </el-form-item>
          <!-- <el-form-item prop="code">
            <el-input
                ref="refCode"
                v-model="loginForm.code"
                placeholder="验证码"
                name="code"
                type="text"
                tabindex="1"
                auto-complete="on"
                @keyup.enter="handleLogin(refLoginForm)">
              <template #append >
                <el-image class="code" :src="codeUrl" @click="getVerifyCode" v-loading="loadingCode" >
                  <template #error>
                    <div @click="getVerifyCode">
                      加载失败
                    </div>
                  </template>
                </el-image>
              </template>
            </el-input>
          </el-form-item>
          -->
          <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:3px;"
                     @click.prevent="handleLogin(refLoginForm)" >立即登录</el-button>
        </el-form>
        <el-footer class="footer-text btnClick">
          <el-checkbox v-model="passwordChecked" label="记住密码" @change="checkLoginChange"></el-checkbox>
          <el-checkbox v-model="autologinChecked" @change="autoLoginChange" label="自动登录"></el-checkbox>
        </el-footer>
        <!--
        <el-popover content="点击切换界面" trigger="hover" placement="top-start">
          <template #reference>
            <svg-icon class="setting" name="gear-fill" size="30" @click="switchSetting"></svg-icon>
          </template>
        </el-popover>
        -->
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, onMounted, ref, reactive} from 'vue'
import TabBtn from "@/layout/TabBtn.vue";
import {validLoginname} from "@/utils/validate";
import { ArrowDownBold } from '@element-plus/icons-vue'
import {Utils} from "@/utils/utils";
import {useRouter} from "vue-router";
import {useUserStore} from "@/store/user";
import {FormInstance} from "element-plus";
import {StorageUtils} from "@/utils/StorageUtils";
import SvgIcon from "@/icons/index.vue";
import {Md5Utils} from "@/utils/Md5Utils";
import {IUser} from "@/iwb/IUser";
export default defineComponent({
  name: "toLogin",
  components: {SvgIcon, TabBtn},
  setup: function (props, context) {
    const refLoginForm = ref<FormInstance>();
    const router = useRouter();
    // @ts-ignore
    const validateLoginname = (rule, value, callback) => {
      if (!value || value.length < 1 || !validLoginname(value)) {
        callback(new Error('请输入正确的登录账号'))
      } else {
        callback()
      }
    }
    // @ts-ignore
    const validatePassword = (rule, value, callback) => {
      if (!value || value.length < 6) {
        callback(new Error('登录密码不能小于六位数'))
      } else {
        callback()
      }
    }
    const codeUrl = ref('');
    const loading = ref(false);
    const autologin = ref(true);
    const currentSideUrl = ref('static/register.jpg');
    const loginForm = reactive({
      loginname: '',
      password: '',
      avatarUrl: '',
      code: '',
      uuid: ''
    });
    const loginRules = reactive({
      loginname: [{required: true, trigger: 'blur', validator: validateLoginname}],
      password: [{required: true, trigger: 'blur', validator: validatePassword}]
    });
    const passwordChecked = ref(false);
    const autologinChecked = ref(false);
    const index = ref(0);

    const loginOptions = ref([{}])

    const querySearch = (queryString: string, cb: any) => {
      const options = loginOptions.value;
      const results = queryString ? options.filter(createFilter(queryString)) : options;
      // 调用 callback 返回建议列表的数据
      cb(results);
    };
    const queryNormalUser = () => {
      /*const user = {} as IUser;
      user.roles = 'ROLE_USER';
      const userStore = useUserStore();
      userStore.getUserInfoByU(user, false).then(res => {
        console.warn(res);
      });*/
    }
    const createFilter = (queryString: string) => {
      return (restaurant: any) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    };
    const checkLoginChange = (value: boolean) => {
      if (!value) {
        autologinChecked.value = false
      }
    };
    const autoLoginChange = (value: boolean) => {
      if (value) {
        passwordChecked.value = value
      }
    };
    const getAvatarUrl = (): void => {
      StorageUtils.getStorage('avatar_url').then((avatarUrl: string) => {
        loginForm.avatarUrl = avatarUrl;
      })
    };
    const getLoginName = () => {
      StorageUtils.getStorage('loginname').then((loginname: string) => {
        loginForm.loginname = loginname;
      })
      /** 密码记住时候，获取 */
      StorageUtils.getStorage('password_checked').then((isChecked: string) => {
        passwordChecked.value = isChecked === 'true';
        if (passwordChecked.value) {
          StorageUtils.getStorage('password').then((password: string) => {
            loginForm.password = password;
          })

        }
      })
      /** 勾选自动登录时候，获取 */
      StorageUtils.getStorage('autologin_checked').then((isAutoChecked: string) => {
        autologinChecked.value = isAutoChecked === 'true';
        if (autologinChecked.value) {
          StorageUtils.getStorage('password').then((password: string) => {
            loginForm.password = password;
          })
        }
      })
    };
    const getLoginRecords = () => {
      /**
       * 获取登录记录信息
       */
      StorageUtils.getStorage('login_records').then((data: string) => {
        loginOptions.value = JSON.parse(data) || [];
      })
    };
    const pushLoginRecord = (option: any) => {
      // @ts-ignore
      const index = loginOptions.value.findIndex(item => item.loginname === option.loginname);
      option.value = option.loginname;
      if (index > -1) {
        loginOptions.value[index] = option;
      } else {
        loginOptions.value.push(option)
      }
      StorageUtils.addStorage('login_records', JSON.stringify(loginOptions.value));
    };
    const handleSelect = (item: any) => {
      loginForm.loginname = item.loginname;
      loginForm.password = item.password;
      loginForm.avatarUrl = item.avatarUrl;
    };
    const loadingCode = ref(false);
    const getVerifyCode = () => {
      loadingCode.value = true;
      const userStore = useUserStore();
      userStore.newVerifyCode().then((res: any)=> {
        //console.log(res);
        codeUrl.value = "data:image/gif;base64," + res.data.code;
        loadingCode.value = false;
        //console.warn(res);
      }).catch(err=>{
        loadingCode.value = false;
        console.error(err);
      })
    }
    const handleLogin = (formEl: FormInstance | undefined) => {
      /** 先检查是否配置了通信服务地址信息 */
      if (!formEl) return;
      const userStore = useUserStore();
      formEl.validate((valid: boolean, fields) => {
        if (valid) {
          loading.value = true
          const encryptLoginForm = {loginname: '', password: '', code: ''}
          encryptLoginForm.loginname = loginForm.loginname;
          encryptLoginForm.password = Md5Utils.b64MD5(loginForm.password);
          encryptLoginForm.code = loginForm.code;
          userStore.loginSystem(encryptLoginForm.loginname, encryptLoginForm.password, encryptLoginForm.code).then(() => {
            let nextRouter = '/';
            //console.warn(nextRouter);
            router.push({path: nextRouter})
            loading.value = false;
            StorageUtils.addStorage('loginname', loginForm.loginname);
            if (passwordChecked) {
              StorageUtils.addStorage('password_checked', passwordChecked.value.toString());
              StorageUtils.addStorage('password', loginForm.password);

              if (autologinChecked) {
                StorageUtils.addStorage('autologin_checked', autologinChecked.value.toString());
              } else {
                StorageUtils.delStorage('autologin_checked');
              }
            } else {
              StorageUtils.delStorage('password_checked');
              StorageUtils.delStorage('password');
              StorageUtils.delStorage('autologin_checked');
            }
            /**
             * 保留登录信息
             */
            pushLoginRecord(Utils.cloneObject(loginForm));
          }).catch(() => {
            getVerifyCode();
            loading.value = false
          })
        } else {
          loading.value = false
          console.log('error submit!!', fields);
          return false
        }
      })
    }
    onMounted(() => {
      const aLogin = router.currentRoute.value.query.autologin;
      autologin.value = aLogin !== null ? !aLogin : autologin.value;
      getAvatarUrl();
      getLoginRecords();
      getLoginName();
      //getVerifyCode();
    })
    const switchSetting = () => {
      context.emit('switchSetting');
    }

    return {
      refLoginForm,
      ArrowDownBold,
      codeUrl,
      loading,
      autologin,
      currentSideUrl,
      loginForm,
      loginRules,
      passwordChecked,
      autologinChecked,
      index,
      loginOptions,
      loadingCode,
      validateLoginname,
      validatePassword,
      querySearch,
      handleSelect,
      handleLogin,
      queryNormalUser,
      checkLoginChange,
      autoLoginChange,
      getAvatarUrl,
      getLoginName,
      getLoginRecords,
      pushLoginRecord,
      switchSetting,
      getVerifyCode
    }
  }
})
</script>

<style scoped lang="scss">
@import "./src/styles/variable.scss";
.to-login-container {
  margin: 0;
  height: 100%;
  width: 100%;
  display: grid;
  justify-content: center;
  align-content: center;
  grid-template-columns: 1fr;
  -webkit-user-select: none;
  -webkit-app-region: drag; // 可拖动
  grid-template-rows: 100%;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 10px;

  .left {
    margin: auto;
    height: 100%;
    width: 100%;
    overflow: hidden;
    background-repeat: no-repeat;
    background-position: center;
    border-bottom-left-radius: 10px;
    border-top-left-radius: 10px;
    background-size: 100% 100%;
  }

  .right {
    //margin: 0 50px;
    display: flex;
    flex-direction: column;
    -webkit-app-region: drag; // 可拖动
    justify-content: center;
    vertical-align: middle;
    text-align: center;
  }

  .welcome {
    top: 0;
    right: 0;
    font-size: 41px;
  }
  .header {
    font-size: 28px;
    line-height: 1.2;
    color: $color-sub-text-base;
  }
  .loginForm {
    -webkit-app-region: no-drag; // 不可拖动
    padding: 0 25px 0 25px;
  }
  :deep(.loginForm) {
    .el-autocomplete {
      position: relative;
      display: block;
      width: 100%;
    }
  }
  .footer-text {
    -webkit-app-region: no-drag; // 不可拖动
    display: flex;
    justify-content: space-between;
    padding: 5px 25px 0 25px;
    z-index: 0;
  }
  .setting {
    position: fixed;
    right: 10px;
    bottom: 10px;
    outline: none;
    z-index: 10;
    -webkit-app-region: no-drag; // 不可拖动
  }
  .code {
    width: 72px;
    height: 30px;
    display: block;
    margin-top: -6px;
    margin-bottom: -6px;
  }
  :deep(.code) {
    .el-loading-spinner {
      margin-top: -18px;
    }
    .circular {
      width: 36px;
      height: 36px;
    }
  }
  :deep(.loginForm) {
    .el-input-group__append {
      padding: 0 !important;
    }
  }
}
</style>
